package com.qire.common.utils;

import android.app.ActivityManager;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;

import com.qire.common.basic.ObjectUtil;
import com.qire.common.basic.StringUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * 操作系统功能工具,如：当前手机系统版本（小米或魅族或原生），拷贝到剪切板等
 */
public class OSUtil {

    /**
     * 系统类型枚举
     */
    public enum SystemType {
        FLY_ME_V4 {
            //Flyme V4的displayId格式为 [Flyme OS 4.x.x.xA]
            //Flyme V5的displayId格式为 [Flyme 5.x.x.x beta]
            @Override
            public boolean isAboveVersion() {
                String displayId = Build.DISPLAY;
                if (StringUtil.notEmpty(displayId) && displayId.contains("Flyme")) {
                    String[] displayIdArray = displayId.split(" ");
                    for (String temp : displayIdArray) {
                        //版本号4以上，形如4.x.
                        if (temp.matches("^[4-9]\\.(\\d+\\.)+\\S*")) {
                            return true;
                        }
                    }
                }
                return false;
            }
        },
        MI_UI_V7 {
            @Override
            public boolean isAboveVersion() {
                try {
                    final Properties properties = new Properties();
                    properties.load(new FileInputStream(new File(Environment.getRootDirectory(), "build.prop")));
                    String uiCode = properties.getProperty(KEY_MI_UI_VERSION_CODE, null);
                    if (uiCode != null) {
                        int code = Integer.parseInt(uiCode);
                        return code >= 5;
                    } else {
                        return false;
                    }

                } catch (final Exception e) {
                    return false;
                }
            }
        },
        MI_UI_V6() {
            @Override
            public boolean isAboveVersion() {
                try {
                    final Properties properties = new Properties();
                    properties.load(new FileInputStream(new File(Environment.getRootDirectory(), "build.prop")));
                    String uiCode = properties.getProperty(KEY_MI_UI_VERSION_CODE, null);
                    if (uiCode != null) {
                        int code = Integer.parseInt(uiCode);
                        return code >= 4;
                    } else {
                        return false;
                    }
                } catch (final Exception e) {
                    return false;
                }
            }
        },
        ANDROID_V23 {
            //Android Api 23以上
            @Override
            public boolean isAboveVersion() {
                return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
            }
        },
        NA {
            @Override
            public boolean isAboveVersion() {
                return false;
            }
        };

        private static final String KEY_MI_UI_VERSION_CODE = "ro.miui.ui.version.code";

        public abstract boolean isAboveVersion();
    }

    /**
     * @return 当前系统版本
     */
    public static SystemType currentSystemType() {
        if (SystemType.FLY_ME_V4.isAboveVersion()) {
            return SystemType.FLY_ME_V4;
        }
        if (SystemType.MI_UI_V7.isAboveVersion()) {
            return SystemType.MI_UI_V7;
        }
        if (SystemType.MI_UI_V6.isAboveVersion()) {
            return SystemType.MI_UI_V6;
        }
        if (SystemType.ANDROID_V23.isAboveVersion()) {
            return SystemType.ANDROID_V23;
        }
        return SystemType.NA;
    }

    /**
     * 拷贝到剪切板
     * @param context 设备上下文
     * @param label 标签
     * @param text 内容
     */
    public static void copyToClipboard(Context context, String label, String text) {
        //获取剪贴板管理器：
        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        // 创建普通字符型ClipData
        ClipData mClipData = ClipData.newPlainText(label, text);
        // 将ClipData内容放到系统剪贴板里。
        cm.setPrimaryClip(mClipData);
    }

    /**
     * 计算剩余内存
     * @param context 设备上下文
     * @return 内存余量(单位:M)
     */
    public static long countRemainMemory(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        am.getMemoryInfo(mi);
        return mi.availMem / (1024 * 1024);
    }

    /**
     * 启动QQ，并跳转到对应QQ号聊天
     * @param context 上下文
     * @param qqNumber QQ号码
     */
    public static void launchQQ(Context context, String qqNumber) {
        if(ObjectUtil.nonNull(context)) {
            String URL_CONTACT = "mqqwpa://im/chat?chat_type=wpa&uin=";
            Uri uri = Uri.parse(URL_CONTACT + qqNumber);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            try {
                context.startActivity(intent);
            } catch (android.content.ActivityNotFoundException e) {
                if (context != null) {
                    ToastHelper.showToast("请先安装QQ");
                }
            }
        }
    }

    /**
     * 启动微信
     * @param context 上下文
     */
	public static void launchWeChat(Context context){
		if(ObjectUtil.nonNull(context)) {
            try {
                Intent intent = context.getPackageManager().getLaunchIntentForPackage("com.tencent.mm");
                if (ObjectUtil.nonNull(intent)) {
                    context.startActivity(intent);
                    return;
                }
            } catch (android.content.ActivityNotFoundException e) {
                e.printStackTrace();
            }
            ToastHelper.showToast("没有安装微信");
		}
	}

    /**
     * 唤起设置面板
     */
    public static void launchSettingPanel(Context context) {
        if(ObjectUtil.nonNull(context)) {
            Intent intent = new Intent();
            try {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                if (Build.VERSION.SDK_INT >= 9) {
                    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    intent.setData(Uri.fromParts("package", context.getPackageName(), null));
                } else if (Build.VERSION.SDK_INT <= 8) {
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
                    intent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
                }
                context.startActivity(intent);
            } catch (Exception e) {//抛出异常就直接打开设置页面
                intent = new Intent(Settings.ACTION_SETTINGS);
                context.startActivity(intent);
            }
        }
    }

    /**
     * 获取渠道号
     * @param context
     * @return 返回保存在  META-INF/channel 里的渠道号
     */
    public static String getChannel(Context context) {
        String sourceDir = context.getApplicationInfo().sourceDir;
        String ret = "";
        ZipFile zipfile = null;
        try {
            zipfile = new ZipFile(sourceDir);
            Enumeration<?> entries = zipfile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = ((ZipEntry) entries.nextElement());
                String entryName = entry.getName();
                if (entryName.startsWith("META-INF/channel")) {
                    ret = entryName;
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (zipfile != null) {
                try {
                    zipfile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        String[] split = ret.split("_");
        if (split != null && split.length >= 2) {
            return ret.substring(split[0].length() + 1);
        } else {
            return "0";
        }
    }
}
